package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"hui-hui/models"
	"time"

	"hui-hui/hui_hui_rpc/hui_hui_rpc"
	"hui-hui/hui_hui_rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListPlanLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListPlanLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPlanLogic {
	return &ListPlanLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListPlanLogic) ListPlan(in *hui_hui_rpc.ListPlanRequest) (*hui_hui_rpc.ListPlanResponse, error) {
	// todo: add your logic here and delete this line
	var plans []struct {
		models.Plan
		UserName string
	}
	var total int64
	var ret hui_hui_rpc.ListPlanResponse
	var data []*hui_hui_rpc.FromListPlan
	key := fmt.Sprintf("%s:%d", in.Title, in.Page)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {
		sql := models.DB.Model(&models.Plan{}).Joins("join users on plans.user_id = users.id").Select("plans.*,users.name as user_name")
		tsql := models.DB.Model(&models.Plan{})
		if in.Title != "" {
			sql = sql.Where("title like ?", "%"+in.Title+"%")
			tsql = tsql.Where("title like ?", "%"+in.Title+"%")
		}
		if sql.Limit(5).Offset(int(in.Page-1)*5).Order("created_at desc").Scan(&plans).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if tsql.Count(&total).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		for _, plan := range plans {
			get := hui_hui_rpc.FromListPlan{
				UserName:  plan.UserName,
				CreatedAt: plan.CreatedAt.String(),
				Title:     plan.Title,
				Image:     plan.Image,
				Des:       plan.Des,
			}
			data = append(data, &get)
		}
		ret = hui_hui_rpc.ListPlanResponse{
			Plans: data,
			Total: total,
		}
		set, _ := json.Marshal(&ret)
		models.RDB.Set(models.Ctx, key, set, 24*time.Hour)
	} else {
		json.Unmarshal([]byte(get), &ret)
	}

	return &ret, nil
}
